package idx

import (
	"errors"
	"sync"
)

type Factory func(key string) (*FileStore, error)

type pool struct {
	mux     sync.Mutex
	fs      map[string]*FileStore
	cap     int
	factory Factory
}

func (p *pool) Get(key string) (*FileStore, error) {
	p.mux.Lock()
	defer p.mux.Unlock()
	if f, ok := p.fs[key]; ok {
		return f, nil
	}
	if len(p.fs) >= p.cap {
		return nil, errors.New("too many files are open")
	}
	f, err := p.factory(key)
	if err != nil {
		return nil, err
	}
	p.fs[key] = f
	return f, nil
}

func (p *pool) Close(key string) error {
	p.mux.Lock()
	defer p.mux.Unlock()
	if f, ok := p.fs[key]; ok {
		if f.Idle() {
			delete(p.fs, key)
		}
	}
	return nil
}
